package net.vkits.api;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiParam;
import net.vkits.anjiamiao.application.ContractApplicationService;
import net.vkits.common.dto.BaseDTO;
import net.vkits.common.dto.Contract;
import org.dozer.DozerBeanMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;


@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-27T05:49:23.577Z")

@Controller
public class ContractApiController implements ContractApi {

    @Resource
    private HttpServletRequest request;
    @Resource
    private DozerBeanMapper mapper;
    @Resource
    private ContractApplicationService contractApplicationService;

    public ResponseEntity<BaseDTO> addContract( @ApiParam(value = "合同基本信息", required = true) @RequestBody Contract contract) {
        final Claims claims = (Claims) request.getAttribute("claims");
        String phone = claims.get("phone").toString();
        contractApplicationService.addContract(contract.getLandlord(), contract.getAccount(), contract.getBank(), contract.getCellphone(), phone);
        BaseDTO baseDTO = new BaseDTO();
        baseDTO.setCode(200);
        baseDTO.setMsg("OK");
        return new ResponseEntity<>(baseDTO, HttpStatus.OK);
    }

    public ResponseEntity<Contract> getContract() {
        final Claims claims = (Claims) request.getAttribute("claims");
        String cellphone = claims.get("phone").toString();
        Optional<net.vkits.anjiamiao.domain.model.Contract> contractOptional = contractApplicationService.getContract(cellphone);
        if (contractOptional.isPresent()) {
            Contract contractDTO = mapper.map(contractOptional.get(), Contract.class);
            return new ResponseEntity<>(contractDTO, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @Override
    public ResponseEntity<String> addPhoto(@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file, @ApiParam(value = "add photo number", required = true) @RequestPart(value = "number", required = true) String number) {
        final Claims claims = (Claims) request.getAttribute("claims");
        String cellphone = claims.get("phone").toString();
        contractApplicationService.addPhoto(file, number, cellphone);
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }
}
